#include "screentestthread.h"
#include <QSqlError>

static char getFtl[30]={"lss100.sys.ftl\r"};
static char getTheaterNo[100] = {"Lss100.sys.theater_number\r"};


QString ScreenTestThread::read_data(char *s, QTcpSocket &socket)
{
    char buf[50];
    socket.write(s, strlen(s));
    if(!socket.waitForBytesWritten())
        throw socket.errorString();
    memset(buf, 0, 50);
    if (!socket.waitForReadyRead())
        throw socket.errorString();
    socket.read(buf, 50);
    return QString::fromLocal8Bit(buf);
}

ScreenTestThread::ScreenTestThread(QObject *parent, QSqlDatabase *db) :
    QThread(parent), stopped(false)
{
    this->db = *db;
    sql = tr("select before_ip, after_ip, theaterNo from screen_test_setup ");
    model = new QSqlQueryModel();
    model->setQuery(sql, this->db);
    if(model->lastError().isValid())
    {
        emit send_msg(tr("屏幕检测出错"));
        emit log_info(sql);
    }

    for(int i = 0; i<model->rowCount(); i++)
    {
        QString before_ip = model->data(model->index(0, 0)).toString();
        QString after_ip = model->data(model->index(0, 1)).toString();
        QString theaterNo = model->data(model->index(0, 2)).toString();

        device_list.push_back({before_ip, after_ip, theaterNo});
    }
}

void ScreenTestThread::run()
{
    QSettings *settings = new QSettings("config.ini", QSettings::IniFormat);
    QTime test_time = settings->value("SCREEN_TEST_TIME").toTime();
    while(!stopped)
    {
//        emit log_info(tr("屏幕检测已经开始"));
        if(test_time != QTime::currentTime())
        {
            continue;
        }
            emit log_info(tr("屏幕检测已经开始"));
            for(int i = 0; i<device_list.size(); i++)
            {
                ScreenTest item;

                if(connect(tcpSocket, device_list.at(i).before_ip, 10001))
                {
                    item.before_value = read_data(getFtl, tcpSocket);
                }
                if(connect(tcpSocket, device_list.at(i).after_ip, 10001))
                {
                    item.after_value = read_data(getFtl, tcpSocket);
                    item.theaterNo = read_data(getTheaterNo, tcpSocket);
                }

                result_list.push_back(item);

            }
            for(int i = 0; i<result_list.size(); i++)
            {
                double before_ftl_df = result_list.at(i).before_value.toDouble();
                double after_ftl_df = result_list.at(i).after_value.toDouble();
                QString theaterNo = result_list.at(i).theaterNo;
                sql = tr("insert into screen_test(reflect_before_value, reflect_after_value, theaterNo,datetime)values('%1', '%2', '%3', CURRENT_TIMESTAMP()); ")
                        .arg(before_ftl_df).arg(after_ftl_df).arg(theaterNo);
                model->setQuery(sql, db);
                if(model->lastError().isValid())
                {
                    emit send_msg(model->lastError().text());
                    emit log_info(sql);
                    qDebug()<<sql<<endl;
                }
            }
        }


}

void ScreenTestThread::Stop(bool flag)
{
    this->stopped = flag;
}

bool ScreenTestThread::connect(QTcpSocket &socket, QString ip, int port)
{
    socket.connectToHost(ip, port);
    if (!socket.waitForConnected(1000)) {
        emit send_msg(tr("连接ip为%1设备出错, 请检查设备或网络环境！").arg(ip));
        return false;
    }
    return true;
}
